<template>
    <div>
        <el-select v-model="province" clearable placeholder="请选择省">
            <el-option
                    v-for="item in provinceOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
            />
        </el-select>
        <el-select v-model="city" clearable placeholder="请选择市" class="mlr" :disabled="!province">
            <el-option
                    v-for="item in cityOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
            />
        </el-select>
        <el-select v-model="area" clearable placeholder="请选择区" :disabled="!province || !city">
            <el-option
                    v-for="item in areaOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
            />
        </el-select>
    </div>
</template>

<script setup lang="ts">
    import PCAData from './lib/pca-code.json'

    defineOptions({
        name: 'SelectArea'
    })
    console.log(PCAData)
    let province = ref<string>('')
    let city = ref<string>('')
    let area = ref<string>('')
    let provinceOptions = ref(PCAData)
    let cityOptions = ref<AreaItem[]>([])
    let areaOptions = ref<AreaItem[]>([])

    interface AreaItem {
        name: string,
        code: string,
        children?: AreaItem[]
    }
    interface Data {
        name: string,
        code: string
    }

    let emits = defineEmits(['change'])

    watch( ()=> province.value, val => {
        if (val) {
           let cities = provinceOptions.value.find(item => item.code == province.value)!.children
            cityOptions.value = cities
        }
        city.value = ''
        area.value = ''
    })
    watch( ()=> city.value, val => {
        if (val) {
            let area = cityOptions.value.find(item => item.code == city.value)!.children!
            areaOptions.value = area
        }
        area.value = ''
    })
    watch( ()=> area.value, val => {
        if (val) {
            let provinceData: Data = {
                code: province.value,
                name: province.value && provinceOptions.value.find(item => province.value== item.code)!.name
            }
            let cityData: Data = {
                code: city.value,
                name: city.value && cityOptions.value.find(item => city.value== item.code)!.name
            }
            let areaData: Data = {
                code: area.value,
                name: area.value && areaOptions.value.find(item => area.value== item.code)!.name
            }
            emits('change', {
                province: provinceData,
                city: cityData,
                area: areaData,
            })
        }
    })
</script>

<style scoped>

</style>
